<template>
  <Layout class="articalManager">
      <div>
        <Form ref="form1" :model="form1"  :label-width="120">
            <Row  class="query-form" style="padding-top: 15px">
                <Col span="7">
                    <FormItem label="标题：">
                        <Input class="query-form-el" type="text" v-model="form1.title"></Input>
                    </FormItem>
                </Col>
                <Col span="7">

                </Col>
                <Col span="7" offset="2">
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button  class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" type="success"  class="ivu-btn-add" icon="md-add" @click="addArtical()">新增</Button>
                </Col>
            </Row>
        </Form>
      </div>
      <!-- 响应结果内容展示 -->
      <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" :loading="buttonLoading"
           stripe border :columns="columns1" :data="resultData">
      </Table>
      <!-- 底部分页条 -->
    <Page :total="dataCount" :page-size="pageSize"
          :page-size-opts="pageSizeArray" @on-change="pageChange"
          @on-page-size-change="pageSizeChange" show-total show-sizer />

    <!--弹出窗  @on-cancel="cancel":当点击取消触发的函数-->

       <Modal  :transfer=false v-model="model1"  :width=800 >
            <Row>
                <Col span="24">
                    <Tabs value="name1" style="margin: 0; padding: 0;">
                        <TabPane label="培训通知" name="name1">
                            <Form ref="formCustom" :model="formCustom" :rules="ruleCustom"  label-position="top">
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23" >
                                        <FormItem label="标题" prop="title">
                                        <Input type="text" v-model="formCustom.title"></Input>
                                        </FormItem>
                                    </Col>


                                </Row>
                                <Row type="flex" justify="center" class="code-row-bg">
                                    <Col span="23">
                                        <FormItem label="附件：">
                                            <div>
                                                <Upload ref="upload"
                                                        :before-upload="beforeUpload"
                                                        :show-upload-list="true"
                                                        :max-size="10240"
                                                        multiple
                                                        type="drag"
                                                        :action="fileUrl">
                                                    <div style="padding: 10px">
                                                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                        <p>点击将文件拖拽到这里上传</p>
                                                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                                    </div>
                                                </Upload>
                                            </div>
                                            <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                                <a @click="downloadFile(formCustom.proposalId,item)">{{ item.fileName }}</a>
                                                <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                                        style="margin-left: 5px;margin-bottom: 3px"/>
                                            </div>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="center" class="code-row-bg">
                                    <Row type="flex" justify="center" class="code-row-bg">
                                        <Col span="23">
                                            <FormItem label="内容" prop="content">
                                                <quill-editor v-model="formCustom.content"  style="height:240px;margin-bottom: 80px"></quill-editor>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Row>
                            </Form>
                        </TabPane>
                        <TabPane label="通知机构"  v-if="formCustom.type=='4'" name="name2">
                            <div style="height: 600px; overflow-y: auto; overflow-x: auto;">
                                <Tree ref="itemTree" :data="orgInfoTree"  :load-data="loadData" show-checkbox></Tree>
                            </div>
                        </TabPane>
                    </Tabs>
                </Col>
            </Row>
           <div slot="footer">
               <Button type="primary"  class='ivu-btn-save' @click="submit('formCustom')" >确定</Button>
               <Button type="text"  class='ivu-btn-cancel'  @click="modalcancel" >取消</Button>
           </div>
        </Modal>

        <Modal class="modal-view-detail" title="资料管理"   :transfer=false   v-model="model2"  :width=800 >
            <Row>
                <Col span="24">
                    <Form ref="showdata" :label-width="160" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="标题" prop="title">
                                      {{formCustom.title}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="发布处室" prop="browse">
                                    {{formCustom.orgName}}
                                </FormItem>
                            </Col>

                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="发布人" prop="userName">
                                      {{formCustom.userName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="发布时间" prop="infoTitle">
                                      {{formCustom.updateDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="附件：">
                                    <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                        <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="内容：" prop="content">
                                    <div v-html="formCustom.content"></div>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
            </div>
        </Modal>

  </layout>

</template>

<script>
    import {
        Api
    } from "../../../../api/index.js"
    import {
        quillEditor
    } from 'vue-quill-editor'
    import {sessionStorage} from '../../../../common/cacheUtils.js';
    export default {
        components:{
            quillEditor
        },
        data() {
            return {
                orgInfoTree: [],
                uploadList:[],
                fileUrl: Api.interestedPartiesUserFile,
                buttonLoading:false,
                add:false,
                typeList:[
                    {
                        name:"通知公告",
                        value:"1",
                    },
                    {
                        name:"最新公文",
                        value:"2",
                    },
                    {
                        name:"会议摘要",
                        value:"3",
                    },
                    {
                        name:"培训通知",
                        value:"4",
                    }
                ],
                form1:{},
                formCustom: {},
                ruleCustom: {
                    title: [
                    { required: true, message: "", trigger: "blur" }
                    ],
                    type: [
                    { required: true, message: "", trigger: "change" }
                    ],
                    content: [{
                        validator: (rule, value, callback) => {
                            if (this.formCustom.content == null || this.formCustom.content == '' || this.formCustom.content == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                },
                title:"",
                resultData:[],
                showdata:{},
                tableHeight: 450,
                pageSizeArray: [5, 10, 20, 50],
                dataCount: 0,
                pageSize:10,
                currentPage: 1,
                columns1: [{
                        title: "序号",
                        width: 80,
                        align: "center",
                        render: (h, params) => {
                            return h('span', params.index + (this.currentPage - 1) * this.pageSize + 1);
                        }
                    },
                    {
                        title: '标题',
                        align: 'center',
                        minWidth: 150,
                        key: 'title'
                    },
                  /*  {
                        title: '类型',
                        align: 'center',
                        width: 300,
                        key: 'browse',
                        render: (h, params) => {
                            return h('div',[
                                (params.row.type === '1' ? '通知公告':params.row.type === '2' ? '最新公文':params.row.type === '3'?'会议摘要':'培训通知')
                            ]);
                        }
                    },*/
                   /* {
                        title: '浏览量',
                        align: 'center',
                        width: 300,
                        key: 'browse'
                    },*/
                    {
                        title: '发布处室',
                        align: 'center',
                        minWidth: 150,
                        key: 'orgName'
                    },
                    {
                        title: '发布人',
                        align: 'center',
                        minWidth: 150,
                        key: 'userName'
                    },
                    {
                        title: '发布时间',
                        align: 'center',
                        minWidth: 150,
                        key: 'updateDate',
                        render:(h,params)=>{
                            return h('div',[
                                (this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                  /*  {
                        title: '内容',
                        align: 'center',
                        ellipsis: true,
                        key: 'content'
                    },*/
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 200,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params, 2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ],
                model1: false,
                model2: false,
                infoId:"",
                file : null,
                picture: '',
                fileName : null,
                downloadUrl : Api.downloadMongoFile
           }
        },
        mounted: function() {
            this.$http.get(Api.queryErJi).then((res) => {})
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            //页面加载执行的查询函数,返回的总条数,激活前端分页插件的页码功能.
            this.query();
            this.getOrgInfoTree();
        },
        methods: {
            query(){
                this.buttonLoading=true
                let data = {
                    startPage: this.currentPage,
                    size: this.pageSize,
                    type:'4'
                };

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.queryAppProposalList;
                this.$http.get(url, {params:data}).then((res) => {
                    if(res.data.status == '200'){
                        this.resultData = res.data.data.data;
                        this.dataCount = res.data.data.totalSize;
                    }else{
                        this.$Message.error("数据获取失败")
                    }
                    this.buttonLoading=false
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            modalcancel() {
                this.model1 = false;
                this.formCustom = {};
            },
            getFiles() {
                let url = this.fileUrl + '/' + this.formCustom.proposalId + '/files/notice'
                this.$http.get(url).then((res) => {
                    if (res.data.result == "success") {
                        this.uploadList = res.data.data
                    }
                })
            },
            beforeUpload(file) {
                let formData = new FormData();
                formData.append("files", file); // 文件对象
                let url = this.fileUrl + '/' + this.formCustom.proposalId + '/files/notice'
                this.$http.post(url, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.info("文件上传成功")
                        this.getFiles();
                    }
                })
                return false
            },
            downloadFile(guideId, file) {
                let url = this.fileUrl + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {

                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },

            remove1(id) {
                let url = this.fileUrl + '/file/' + id;
                this.$http.delete(url).then((res) => {
                    this.getFiles()
                })
            },
            submit() {
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
                        let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                        let userId = sessionStorage('userId').getObject('userId').userId;

                        if(this.add){
                            this.formCustom.createUserId = userId;
                            this.formCustom.createOrgId = orgId;
                            this.$http.post(Api.saveAppProposal, this.formCustom).then((res) => {
                                if (this.formCustom.type === '4'){
                                    let tree =  this.$refs.itemTree.getCheckedAndIndeterminateNodes();
                                    let checkNode = [];
                                    tree.map((i, j)=>{
                                        checkNode.push({proposalId:this.formCustom.proposalId,orgId: i.orgId,iterator:i.children.length==0?'1':'0'});
                                    });
                                    this.$http.post(Api.saveReceiptToOrg + "/"+ this.formCustom.proposalId,
                                        checkNode).then((res) => {}).catch(e => {})
                                }
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                console.log(e)
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }else{
                            this.formCustom.updateUserId = userId;
                            this.formCustom.updateOrgId = orgId;
                            this.$http.post(Api.updateAppProposal, this.formCustom).then((res) => {
                                if (this.formCustom.type === '4'){
                                    let tree =  this.$refs.itemTree.getCheckedAndIndeterminateNodes();
                                    let checkNode = [];
                                    tree.map((i, j)=>{
                                        checkNode.push({proposalId:this.formCustom.proposalId,orgId: i.orgId,iterator:i.children.length==0?'1':'0'});
                                    });
                                    this.$http.post(Api.saveReceiptToOrg + "/"+ this.formCustom.proposalId,
                                        checkNode).then((res) => {}).catch(e => {})
                                }
                                this.$Message.success("保存成功")
                                this.model1 = false;
                                this.query();
                            }).catch(e => {
                                this.model1 = false;
                                this.query();
                                this.$Message.error("数据获取失败")
                            })
                        }

                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            addArtical() {
                this.uploadList = [];
                this.add = true;
                this.model1 = true;
                this.formCustom = {
                    proposalId:this.get_uuid(),
                    type:'4',
                }
                this.getOrgInfoTree();
            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },
            //重置输入框
            reset() {
                this.form1 = {};
            },
            pageChange(pageNum) {
                this.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pageSize = pageSize;
                this.query();
            },
            showData(data, flag) {
                if (flag == 1) {
                    this.formCustom = data.row;
                    this.formCustom.createDate = this.formatDate(new Date(this.formCustom.createDate), 'yyyy-MM-dd');
                    this.formCustom.updateDate = this.formatDate(new Date(this.formCustom.updateDate), 'yyyy-MM-dd');
                    this.getFiles();
                    this.model2 = true;
                } else {
                    //修改页面
                    this.add = false;
                    this.formCustom = JSON.parse(JSON.stringify(data.row));
                    this.getFiles();
                    this.formCustom.createDate = this.formatDate(new Date(this.formCustom.createDate), 'yyyy-MM-dd');
                    this.formCustom.updateDate = this.formatDate(new Date(this.formCustom.updateDate), 'yyyy-MM-dd');
                    this.model1 = true;
                    this.getOrgInfoTreeByProposalId(this.formCustom.proposalId);
                }
            },
            deleteData(params) {
                let istrue = confirm("是否确定删除?");
                if (istrue) {
                    this.$http.delete(Api.deleteAppProposal + '/' + params.row.proposalId).then((res) => {
                        if (res.data.status == 200) {
                            this.$Message.info('删除成功');
                            this.query();
                        } else {
                            this.$Message.info('删除失败');
                        }
                    }).catch(e=>{
                        this.$Message.error("修改失败");
                    });
                }
            },
            getOrgInfoTree(){
                let companyId = sessionStorage('userId').getObject('userId').companyId;
                let companyName = sessionStorage('userId').getObject('userId').companyName;
                this.orgInfoTree = [{orgId:companyId,title:companyName,children:[],expand:true}];
            	this.$http.get(Api.queryOrg, {
					params: {
                        parentId: companyId,
                        codeAffordIf : 0
					}
				}).then(res => {
					res.data.data.map(i => {
						i.title = i.orgName;
						delete i['orgName'];
						i.loading = false;
						i.children = [];
					});
                    this.$set(this.orgInfoTree[0],'children',res.data.data);
				}).catch(e => {
					this.$Message.error('请求失败');
				})
            },
            getOrgInfoTreeByProposalId(proposalId){
                let companyId = sessionStorage('userId').getObject('userId').companyId;
                let companyName = sessionStorage('userId').getObject('userId').companyName;
                this.orgInfoTree = [{orgId:companyId,title:companyName,children:[],expand:true}];
            	this.$http.get(Api.queryOrgByProposalId+"/"+companyId+
                "/"+proposalId).then(res => {
					res.data.data.map(i => {
						i.title = i.orgName;
						delete i['orgName'];
						i.loading = false;
						i.children = [];
					})
                    this.$set(this.orgInfoTree[0],'children',res.data.data);
				}).catch(e => {
					this.$Message.error('请求失败');
				})
            },
            loadData(item, callback) {
				item.loading = true;
                if(this.add){
                    this.$http.get(Api.queryOrg, {
                        params: {
                            parentId: item.orgId,
                            codeAffordIf : 0
                        }
                    }).then(res => {
                        item.loading = false;
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                i.title = i.orgName
                                delete i['orgName']
                                i.loading = false;
                                i.children = [];
                            })
                            item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['children'];
                            delete item['loading'];
                        }
                    }).catch(e => {
                        console.log(e);
                        this.$Message.error('请求失败');
                    })
                }else{
                    this.$http.get(Api.queryOrgByProposalId+"/"+item.orgId+"/"+this.formCustom.proposalId).then(res => {
                        item.loading = false;
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                i.title = i.orgName
                                delete i['orgName']
                                i.loading = false;
                                i.children = [];
                            })
                            item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['children'];
                            delete item['loading'];
                        }
                    }).catch(e => {
                        console.log(e);
                        this.$Message.error('请求失败');
                    })
                }
			},
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        }
    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';
</style>
